package com.example.springboot.hl7;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v24.datatype.MSG;
import ca.uhn.hl7v2.model.v24.datatype.XPN;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.STF;
import ca.uhn.hl7v2.protocol.ReceivingApplication;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

@Slf4j
public class HL7MessageReceivingApplication implements ReceivingApplication {

    private HL7ServiceInfo hl7ServiceInfo;

    public HL7MessageReceivingApplication(HL7ServiceInfo hl7ServiceInfo) {
        this.hl7ServiceInfo = hl7ServiceInfo;
    }

    @Override
    public Message processMessage(Message message, Map<String, Object> map) throws HL7Exception {
        Message messageAck = null;
        try {
            messageAck = message.generateACK();
            log.info("HL7MessageReceivingApplication:processMessage:接收消息...开始");
            log.info("HL7MessageReceivingApplication:processMessage:消息内容:{}",message.printStructure());
            hl7ServiceInfo.setLastMessage(JSON.toJSONString(map));
            MSH msh = (MSH) message.get("MSH");
            MSG msg9 = msh.getMsh9_MessageType();
            String msg9_1 = msg9.getMsg1_MessageType().getValue();
            String msg9_2 = msg9.getMsg2_TriggerEvent().getValue();
            String msg9_3 = msg9.getMsg3_MessageStructure().getValue();
            if ("PMU".equals(msg9_1) && "B01".equals(msg9_2) && "PMU_B01".equals(msg9_3)){
                log.info("HL7MessageReceivingApplication:processMessage:新增职工信息...");
            }
            else if ("PMU".equals(msg9_1) && "B02".equals(msg9_2) && "PMU_B01".equals(msg9_3)){
                log.info("HL7MessageReceivingApplication:processMessage:更新职工信息...");
            }else {
                return messageAck;
            }
            STF stf = (STF) message.get("STF");
            XPN xpn = stf.getStaffName(0);
            String staffName = xpn.getGivenName().getValue();
        } catch (IOException e) {
            e.printStackTrace();
            hl7ServiceInfo.setRunMsg(e.getMessage());
        }
        log.info("HL7MessageReceivingApplication:processMessage:接收消息...结束");
        return messageAck;
    }

    @Override
    public boolean canProcess(Message message) {
        return true;
    }
}
